<template>
  <view class="container">
    <!-- 进度与标题区域 -->
    <view class="header">
      <text class="title">{{ surveyInfo.title || '问卷调查' }}</text>
      <view class="progress-box">
        <text class="progress-text">{{ current }}/{{ total }}</text>
        <view class="progress-bar">
          <view class="progress" :style="{ width: progressWidth }"></view>
        </view>
      </view>
    </view>

    <!-- 题目区域 -->
    <view class="question-card" v-if="currentQuestion">
      <!-- 题目类型和标题 -->
      <text class="question-type">
        {{ getQuestionTypeName(currentQuestion.type) }} {{ currentQuestion.title }}
        <text class="required" v-if="currentQuestion.required">*</text>
      </text>

      <!-- 题目图片 -->
      <image class="question-img" :src="currentQuestion.image" mode="widthFix" v-if="currentQuestion.image"></image>

      <!-- 单选题 -->
      <view class="options" v-if="currentQuestion.type === 'radio'">
        <button class="option-btn" :class="{ 'selected': answers[currentQuestion.question_key] === option.value }"
          v-for="(option, index) in currentQuestion.options" :key="index"
          @click="handleAnswer(currentQuestion.id, option.value)">
          {{ option.text || option.label }}
        </button>
      </view>

      <!-- 多选题 -->
      <view class="options" v-if="currentQuestion.type === 'checkbox'">
        <button class="option-btn checkbox"
          :class="{ 'selected': getAnswerArray(currentQuestion.id).includes(option.value) }"
          v-for="(option, index) in currentQuestion.options" :key="index"
          @click="handleMultiAnswer(currentQuestion.id, option.value)">
          <view class="checkbox-icon" :class="{ 'checked': getAnswerArray(currentQuestion.id).includes(option.value) }">
            <text v-if="getAnswerArray(currentQuestion.id).includes(option.value)">✓</text>
          </view>
          {{ option.text || option.label }}
        </button>
      </view>

      <!-- 填空题 -->
      <view class="textarea-container" v-if="currentQuestion.type === 'textarea'">
        <textarea class="answer-textarea" placeholder="请输入答案..." v-model="answers[currentQuestion.question_key]"
          @input="handleAnswer(currentQuestion.id, $event.target.value)"
          :class="{ 'selected': answers[currentQuestion.question_key] && answers[currentQuestion.question_key].trim() !== '' }"></textarea>
      </view>
    </view>

    <!-- 底部区域 -->
    <view class="footer">
      <!-- 左侧：题卡按钮 -->
      <button class="card-btn" @click="toggleQuestionNav">
        {{ showQuestionNav ? '收起' : '题卡' }}
      </button>

      <!-- 右侧：切换题目按钮 -->
      <view class="nav-buttons">
        <button class="nav-btn prev-btn" @click="prevQuestion" :disabled="current <= 1">
          上一题
        </button>
        <button class="nav-btn next-btn" @click="handleNextOrSubmit" :disabled="shouldDisableNextButton">
          {{ isLastQuestion && allAnswered ? '提交' : '下一题' }}
        </button>
      </view>
    </view>

    <!-- 题卡导航区域 -->
    <view class="question-nav" v-if="showQuestionNav">
      <view class="question-nav-item" v-for="(item, index) in total" :key="index" :class="[
        { 'active': index + 1 === current },
        { 'answered': answeredQuestions.includes(index + 1) }
      ]" @click="goToQuestion(index + 1)">
        {{ index + 1 }}
      </view>
    </view>

  </view>
</template>

<script>
export default {
onLoad(options){
  console.dir(options.surveyId);
  // 获取问卷ID并加载问卷数据
  if (options.surveyId) {
    this.surveyId = options.surveyId;
    this.fetchSurveyDetails();
  } else {
    uni.showToast({
      title: '问卷ID不能为空',
      icon: 'none'
    });
  }
},
  data() {
    return {
      // 问卷ID
      surveyId: null,
      
      // 问卷信息
      surveyInfo: {
        title: '',
        description: '',
        estimated_time: 0,
        participants: 0,
        reward: ''
      },
      
      // 题目列表
      questionList: [],

      // 状态管理
      current: 1,
      answers: {}, // 存储用户答案
      showQuestionNav: false,
      shouldDisableNextButton: false,
      isLoading: false
    };
  },

  computed: {
    total() {
      return this.questionList.length;
    },
    isCurrentAnswered() {
      return this.currentQuestion ? this.isQuestionAnswered(this.currentQuestion.id) : false;
    },
    currentQuestion() {
      return this.questionList[this.current - 1] || null;
    },
    progressWidth() {
      return (this.current / this.total) * 100 + '%';
    },
    answeredQuestions() {
      return this.questionList
        .filter(question => this.isQuestionAnswered(question.id))
        .map(question => question.id);
    },
    allAnswered() {
      // 检查是否所有题目都已回答
      return this.questionList.every(question => this.isQuestionAnswered(question.id));
    },
    isLastQuestion() {
      return this.current === this.total;
    }
  },

  methods: {
    getQuestionTypeName(type) {
      const typeMap = {
        radio: '【单选题】',
        checkbox: '【多选题】',
        textarea: '【填空题】'
      };
      return typeMap[type] || '【题目】';
    },

    // 获取答案数组（用于多选题）
    getAnswerArray(questionId) {
      const question = this.questionList.find(q => q.id === questionId);
      if (!question) return [];
      return Array.isArray(this.answers[question.question_key]) ? this.answers[question.question_key] : [];
    },

    // 判断题目是否已回答
    isQuestionAnswered(questionId) {
      const question = this.questionList.find(q => q.id === questionId);
      if (!question) return false;

      const answer = this.answers[question.question_key];

      if (question.type === 'radio' || question.type === 'textarea') {
        return !!answer && answer.toString().trim() !== '';
      } else if (question.type === 'checkbox') {
        return Array.isArray(answer) && answer.length > 0;
      }

      return false;
    },

    handleAnswer(questionId, value) {
      // 使用question_key作为键，而不是id
      const question = this.questionList.find(q => q.id === questionId);
      if (question) {
        this.answers[question.question_key] = value;
      }
    },

    handleMultiAnswer(questionId, optionText) {
      // 使用question_key作为键，而不是id
      const question = this.questionList.find(q => q.id === questionId);
      if (question) {
        if (!Array.isArray(this.answers[question.question_key])) {
          this.answers[question.question_key] = [];
        }

        const index = this.answers[question.question_key].indexOf(optionText);
        if (index > -1) {
          this.answers[question.question_key].splice(index, 1);
        } else {
          this.answers[question.question_key].push(optionText);
        }
      }
    },

    prevQuestion() {
      if (this.current > 1) this.current--;
    },
    handleNextOrSubmit() {
      if (this.isLastQuestion && this.allAnswered) {
        // 最后一题且全部回答，执行提交
        this.shouldDisableNextButton = false
        this.submitAnswers();
      } else if (!this.isLastQuestion) {
        // 非最后一题，执行下一题
        this.nextQuestion();
      }
    },
    nextQuestion() {
      if (this.current < this.total) this.current++;
    },

    goToQuestion(index) {
      if (index >= 1 && index <= this.total) {
        this.current = index;
        this.showQuestionNav = false;
      }
    },

    toggleQuestionNav() {
      this.showQuestionNav = !this.showQuestionNav;
    },

    // 获取问卷详情
    fetchSurveyDetails() {
      this.isLoading = true;
      
      // 显示加载提示
      uni.showLoading({
        title: '加载中...'
      });
      
      // 构建API请求URL
      const apiUrl = 'https://wxapi.xiaoyiwl.cn/wx_questionnare/get_survey_details.php';
      
      // 发起请求
      uni.request({
        url: apiUrl,
        method: 'GET',
        data: {
          surveyId: this.surveyId
        },
        success: (res) => {
          // 隐藏加载提示
          uni.hideLoading();
          this.isLoading = false;
          
          console.log('API返回数据:', res.data);
          
          // 检查返回数据
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 更新问卷信息
            this.surveyInfo = res.data.data.survey;
            
            // 处理并转换问题数据格式以适应组件
            this.processQuestionData(res.data.data.questions);
            
            // 如果没有题目，显示提示
            if (this.questionList.length === 0) {
              uni.showToast({
                title: '该问卷暂无题目',
                icon: 'none'
              });
            }
          } else {
            // 处理错误情况
            console.error('获取问卷详情失败:', res);
            uni.showToast({
              title: res.data?.message || '获取问卷详情失败',
              icon: 'none'
            });
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        },
        fail: (err) => {
          // 隐藏加载提示
          uni.hideLoading();
          this.isLoading = false;
          
          // 显示错误提示
          console.error('请求失败:', err);
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      });
    },
    
    // 处理问题数据，将API返回的格式转换为组件需要的格式
    processQuestionData(questions) {
      if (!Array.isArray(questions)) {
        console.error('问题数据格式错误:', questions);
        this.questionList = [];
        return;
      }
      
      this.questionList = questions.map((question, index) => {
        // 处理选项数据
        const options = Array.isArray(question.options) ? question.options.map(opt => {
          return {
            text: opt.label || opt.text || '',  // 使用label作为显示文本
            value: opt.value || '',
            score: parseInt(opt.score || 0)
          };
        }) : [];
        
        // 创建符合组件格式的问题对象
        return {
          id: index + 1,  // 使用索引+1作为ID
          question_key: question.question_key || '',
          type: question.type || 'radio',
          title: question.title || '未命名题目',
          required: true,  // 默认必填
          options: options,
          correct: question.correct || '',
          analysis: question.analysis || '',
          score: parseInt(question.score || 0),
          image: question.image || null
        };
      });
      
      console.log('处理后的问题列表:', this.questionList);
    },
    
    // 提交答案
    submitAnswers() {
      // 检查是否所有必填题都已回答
      if (!this.allAnswered) {
        uni.showToast({
          title: '请完成所有题目后再提交',
          icon: 'none'
        });
        return;
      }

      // 提交到后端进行判分
      this.submitAnswersToBackend();
    },
    calculateScore() {
      let totalScore = 0

      this.questionList.forEach((question) => {
        const userAnswer = this.answers[question.question_key]
        const questionScore = question.score || 0

        // 单选题得分逻辑
        if (question.type === 'radio' && userAnswer) {
          // 找到用户选择的选项，累加其分值
          const selectedOption = question.options.find(option => option.value === userAnswer);
          totalScore += selectedOption?.score || 0;
        }

        // 多选题得分逻辑（只加正确选项的分，错误选项不扣分）
        if (question.type === 'checkbox' && Array.isArray(userAnswer)) {
          userAnswer.forEach(answerValue => {
            const selectedOption = question.options.find(option => option.value === answerValue);
            // 只有正确选项才加分（避免错误选项得分）
            if (question.correct && typeof question.correct === 'string') {
              // 处理字符串格式的correct
              try {
                const correctAnswers = JSON.parse(question.correct);
                if (Array.isArray(correctAnswers) && correctAnswers.includes(answerValue)) {
                  totalScore += selectedOption?.score || 0;
                }
              } catch (e) {
                // 如果不是有效的JSON，尝试直接比较
                if (question.correct === answerValue) {
                  totalScore += selectedOption?.score || 0;
                }
              }
            } else if (Array.isArray(question.correct) && question.correct.includes(answerValue)) {
              totalScore += selectedOption?.score || 0;
            }
          });
        }

        // 填空题得分逻辑（完全正确才给分）
        if (question.type === 'textarea' && userAnswer && question.correct) {
          // 忽略空格和大小写差异（可根据需求调整）
          const normalizedAnswer = userAnswer.toString().trim().toLowerCase();
          const normalizedCorrect = question.correct.toString().trim().toLowerCase();
          if (normalizedAnswer === normalizedCorrect) {
            totalScore += questionScore;
          }
        }
      });

      return totalScore;
    },

    // 提交答案到后端进行判分
    async submitAnswersToBackend() {
      try {
        // 构建提交数据格式
        const submitData = {
          survey_id: this.surveyId,
          user_id: uni.getStorageSync('user_id') || 'anonymous', // 获取用户ID
          answers: this.formatAnswersForBackend(),
          
        };

        console.log('提交的数据:', submitData);

        // 显示加载提示
        uni.showLoading({
          title: '提交中...'
        });

        // 发送请求到后端
        const response = await new Promise((resolve, reject) => {
          uni.request({
            url: 'https://wxapi.xiaoyiwl.cn/wx_questionnare/ScoringApi.php',
            method: 'POST',
            data: submitData,
            header: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + uni.getStorageSync("token")
            },
            success: resolve,
            fail: reject
          });
        });

        uni.hideLoading();

        if (response.data.code === 200) {
          // 提交成功，显示结果
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });

          // 可以导航到结果页面，传递核心结果数据
          setTimeout(() => {
            const resultData = response.data.data;
            const params = [
              `score=${resultData.score}`,
              `correctCount=${resultData.correct_count}`,
              `wrongCount=${resultData.wrong_count}`,
              `totalQuestions=${resultData.total_questions}`,
              `correctRate=${resultData.correct_rate}`,
              `commentTitle=${encodeURIComponent(resultData.comment.title)}`,
              `commentContent=${encodeURIComponent(resultData.comment.content)}`
            ].join('&');
            
            uni.navigateTo({
              url: `./overcome?${params}`
            });
          }, 1500);
        } else {
          throw new Error(response.data.message || '提交失败');
        }
      } catch (error) {
        uni.hideLoading();
        console.error('提交答案失败:', error);
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        });
      }
    },

    // 格式化答案数据供后端使用
    formatAnswersForBackend() {
      const formattedAnswers = [];

      this.questionList.forEach(question => {
        const userAnswer = this.answers[question.question_key];
        
        if (userAnswer !== undefined && userAnswer !== null) {
          if (question.type === 'radio' || question.type === 'textarea') {
            // 单选题和填空题
            formattedAnswers.push({
              question_key: question.question_key,
              question_type: question.type,
              answer_value: userAnswer,
              selected_options: question.type === 'radio' ? [userAnswer] : []
            });
          } else if (question.type === 'checkbox' && Array.isArray(userAnswer)) {
            // 多选题
            formattedAnswers.push({
              question_key: question.question_key,
              question_type: question.type,
              answer_value: userAnswer.join(','), // 多选答案用逗号分隔
              selected_options: userAnswer
            });
          }
        }
      });

      return formattedAnswers;
    }
  }
}

</script>



<style>
.container {
  padding: 20rpx;
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  /* 给底部固定栏留出空间 */
  padding-bottom: 100rpx;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 头部样式 */
.header {
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}

.progress-box {
  width: 100%;
}

.progress-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.progress-bar {
  height: 12rpx;
  background: #eee;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: #00cc99;
  transition: width 0.3s;
}

/* 结果按钮 */
.result-btn {
  margin: 20rpx 0;
  width: 100%;
}

/* 题目卡片 */
.question-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.question-type {
  font-size: 32rpx;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.required {
  color: #ff4d4f;
  margin-left: 8rpx;
}

.question-img {
  width: 100%;
  margin: 20rpx 0;
  border-radius: 8rpx;
}

/* 选项样式 */
.options {
  margin-top: 20rpx;
}

.option-btn {
  width: 100%;
  padding: 20rpx;
  margin-bottom: 15rpx;
  text-align: left;
  background: #f5f5f5;
  border-radius: 10rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
}

.option-btn.checkbox {
  padding-left: 60rpx;
  position: relative;
}

.checkbox-icon {
  position: absolute;
  left: 20rpx;
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #999;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-icon.checked {
  background: #00cc99;
  border-color: #00cc99;
  color: white;
}

/* 填空样式 */
.textarea-container {
  margin-top: 20rpx;
}

.answer-textarea {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx;
  border: 2rpx solid #eee;
  border-radius: 10rpx;
  font-size: 28rpx;
  resize: vertical;
}

/* 状态样式 */
.selected {
  background: #e6f7ff;
  border: 2rpx solid #1890ff;
}

.correct {
  background: #f6ffed;
  border-color: #52c41a;
}

.incorrect {
  background: #fff1f0;
  border-color: #f5222d;
}

/* 底部固定导航栏 - 核心优化点 */
.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 90rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.card-btn {
  padding: 0 25rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: #f0f0f0;
  color: #333;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.nav-buttons {
  display: flex;
  gap: 15rpx;
}

.nav-btn {
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.prev-btn {
  background: #f0f0f0;
  color: #333;
}

.next-btn {
  background: #00cc99;
  color: white;
}

/* 底部区域样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 8px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
  height: 50px;
  box-sizing: border-box;
}

/* 题卡按钮 */
.card-btn {
  width: 80px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  margin-right: 10px;
}

/* 导航按钮容器 */
.nav-buttons {
  display: flex;
  flex: 1;
  gap: 10px;
}

.nav-btn {
  flex: 1;
  padding: 0;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  border: none;
  text-align: center;
}

.prev-btn {
  color: #000;
  background-color: rgb(178, 243, 60);
}

.next-btn {
  color: rgb(178, 243, 60);
  background-color: rgb(0, 0, 0);
}

.nav-btn:disabled {
  background-color: #ccc;
  opacity: 0.7;
}

/* 题卡导航样式 */
.question-nav {
  position: fixed;
  bottom: 50px;
  /* 位于底部按钮上方 */
  left: 0;
  right: 0;
  padding: 10px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 90;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
  box-sizing: border-box;
}

.question-nav-item {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;
  border-radius: 50%;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.question-nav-item.active {
  background-color: #007aff;
  color: white;
  font-weight: bold;
}

.question-nav-item.answered {
  background-color: #e6f7f0;
  color: #00cc99;
}

.question-nav-item.correct {
  background-color: #00cc99;
  color: white;
}

.question-nav-item.incorrect {
  background-color: #ff4d4f;
  color: white;
}
</style>